<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-tile">
        {{ $t("route.desktopManage") }}
        <i v-if="false" class="iconfont iconzhongyiicon_gaojing"></i>
      </div>
      <div class="left-wrapper"></div>
      <div class="right-wrapper"></div>
    </div>
    <div class="page-content">
      <el-scrollbar class="content-wrapper">
        <el-card>
          <el-tabs v-model="activeName" @change="handleChange">
            <el-tab-pane
              :label="$t('route.HorizonDesktopPools')"
              name="HorizonTable"
            >
              <basic-table
                tableName="HorizonTable"
                
                ref="HorizonTable"
                :pageMethod="
                  (params) => {
                    params.type = 'HorizonView'; // 桌面池类型
                    if (tableSearch) {
                      params.page = 1;
                      tableSearch = false;
                    }
                    params.search = this.searchValue;
                    if (this.Horizon_resource_value && this.Horizon_resource_value !== 'all') {
                      params.resource_pool = this.Horizon_resource_value; // 资源池ID
                    } else {
                      delete params.resource_pool;
                    }
                    if (this.Horizon_tenant_value && this.Horizon_tenant_value !== 'all') {
                      params.resource_id = this.Horizon_tenant_value; // 资源租户ID
                    } else {
                      delete params.resource_id;
                    }
                    return $pandaApi.getDesktopPools(params);
                  }
                "
              >
                <template #table-options="tableSlotData">
                  <!-- 搜索 -->
                  <div class="table-left-options">
                    <el-button
                      class="icon-button setting-button"
                      style="width: auto; margin-right: 10px"
                      @click="syncDesktopPool"
                      :disabled="loading"
                      :loading="loading"
                      v-if="isAllHorizon"
                    >
                      <i
                        v-show="!loading"
                        class="iconfont iconzhongyiicon_tongbu"
                        style="font-size: 12px; margin-right: 5px"
                      ></i>
                      <span style="font-size: 12px">{{
                        $t("desktopManage.operation.synchronizeNow")
                      }}</span>
                    </el-button>
                  </div>
                  <div class="table-right-options">
                    <el-select
                      style="margin-right: 10px"
                      size="medium"
                      v-model="Horizon_resource_value"
                      @change="getHorizonResourceData(true)"
                      :placeholder="$t('desktopManage.message.selectPool')"
                      :disabled="loading"
                      filterable default-first-option
                    >
                      <el-option
                        v-for="(item, index) in HorizonResource_options"
                        :key="index"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                    <el-select
                      style="margin-right: 10px"
                      size="medium"
                      v-model="Horizon_tenant_value"
                      @change="tableSlotData.table.refresh(true)"
                      :placeholder="$t('desktopManage.message.selectUser')"
                      :disabled="loading || Horizon_tenant_value === 'all'"
                      filterable default-first-option
                    >
                      <el-option
                        v-for="(item, index) in HorizonTenant_options"
                        :key="index"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                    <el-input
                      :placeholder="$t('desktopManage.message.searchPools')"
                      v-model="searchValue"
                      style="width: 200px"
                      :disabled="loading"
                      @keyup.enter.native="tableSearchChange(tableSlotData)"
                    >
                    </el-input>
                    <el-button
                      @click="tableSearchChange(tableSlotData)"
                      type="primary"
                      style="margin-left: 10px"
                      >{{ $t("common.search") }}</el-button
                    >
                  </div>
                </template>
                <template #table-column="tableSlotData">
                  <el-table-column
                    type="selection"
                    width="40"
                    align="center"
                  ></el-table-column>
                  <!-- 资源池 -->
                  <el-table-column
                    prop="resource_pool_name"
                    :label="$t('desktopManage.resourcePool')"
                  >
                  </el-table-column>
                  <!-- 普通版租户 -->
                  <el-table-column
                    prop="resource_name"
                    :label="$t('route.resourceHorizon')"
                  >
                  </el-table-column>
                  <!-- 桌面池 -->
                  <el-table-column
                    prop="name"
                    :label="$t('desktopManage.desktopPool')"
                  >
                  </el-table-column>
                  <!-- 桌面数量 -->
                  <el-table-column
                    prop="desktop_num"
                    :label="$t('desktopManage.desktop')"
                  >
                  </el-table-column>
                  <el-table-column :label="$t('common.action')" width="150">
                    <!-- 管理桌面 -->
                    <template #default="props">
                      <link-button
                        :content="
                          $t('desktopManage.operation.managementDesktop')
                        "
                        :size="10"
                        :font-size="'12px'"
                        @click="
                          $router.push({
                            name: 'HorizonDesktopPoolDetail',
                            query: {
                              poolid: props.row.id,
                            },
                          }).catch(()=>{})
                        "
                      />
                    </template>
                  </el-table-column>
                </template>
              </basic-table>
            </el-tab-pane>
            <el-tab-pane :label="$t('route.DaaSDesktopPools')" name="DaasTable">
              <basic-table
                tableName="DaasTable"
                
                ref="DaasTable"
                :pageMethod="
                  (params) => {
                    params.type = 'HorizonDaas';
                    if (tableSearch) {
                      params.page = 1;
                      tableSearch = false;
                    }
                    params.search = this.searchValue;
                    if (this.resource_value && this.resource_value !== 'all') {
                      params.resource_pool = this.resource_value;
                    } else {
                      delete params.resource_pool;
                    }
                    if (this.tenant_value && this.tenant_value !== 'all') {
                      params.resource_id = this.tenant_value;
                    } else {
                      delete params.resource_id;
                      delete params.respurcec_type;
                    }
                    return $pandaApi.getDesktopPools(params);
                  }
                "
              >
                <template #table-options="tableSlotData">
                  <!-- 搜索 -->
                  <div class="table-left-options">
                    <el-button
                      class="icon-button setting-button"
                      style="width: auto; margin-right: 10px"
                      @click="syncDesktopPool"
                      :disabled="loading"
                      :loading="loading"
                      v-if="isAllDass"
                    >
                      <i
                        v-show="!loading"
                        class="iconfont iconzhongyiicon_tongbu"
                        style="font-size: 12px; margin-right: 5px"
                      ></i>
                      <span style="font-size: 12px">{{
                        $t("desktopManage.operation.synchronizeNow")
                      }}</span>
                    </el-button>
                  </div>
                  <div class="table-right-options">
                    <el-select
                      style="margin-right: 10px"
                      size="medium"
                      v-model="resource_value"
                      @change="getResourceData(true)"
                      :placeholder="$t('desktopManage.message.selectPool')"
                      :disabled="loading"
                      filterable default-first-option
                    >
                      <el-option
                        v-for="(item, index) in resource_options"
                        :key="index"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                    <el-select
                      style="margin-right: 10px"
                      size="medium"
                      v-model="tenant_value"
                      @change="tableSlotData.table.refresh"
                      :placeholder="$t('desktopManage.message.selectUser')"
                      :disabled="loading || tenant_value === 'all'"
                      filterable default-first-option
                    >
                      <el-option
                        v-for="(item, index) in tenant_options"
                        :key="index"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                    <el-input
                      :placeholder="$t('desktopManage.message.searchPools')"
                      v-model="searchValue"
                      style="width: 200px"
                      :disabled="loading"
                      @keyup.enter.native="tableSearchChange(tableSlotData)"
                    >
                    </el-input>
                    <el-button
                      @click="tableSearchChange(tableSlotData)"
                      type="primary"
                      style="margin-left: 10px"
                      >{{ $t("common.search") }}</el-button
                    >
                  </div>
                </template>
                <template #table-column="tableSlotData">
                  <!-- <el-table-column
                    type="selection"
                    width="40"
                    align="center"
                  ></el-table-column> -->
                  <!-- 资源池 -->
                  <el-table-column
                    prop="resource_pool_name"
                    :label="$t('desktopManage.resourcePool')"
                  >
                  </el-table-column>
                  <!-- 租户 -->
                  <el-table-column
                    prop="resource_name"
                    :label="$t('desktopManage.daaSTenants')"
                  >
                  </el-table-column>
                  <!-- 桌面池 -->
                  <el-table-column
                    prop="name"
                    :label="$t('desktopManage.desktopPool')"
                  >
                  </el-table-column>
                  <!-- 操作系统 -->
                  <el-table-column
                    prop="os_type"
                    :label="$t('desktopManage.operatingSystem')"
                  >
                  </el-table-column>
                  <!-- 桌面数量 -->
                  <el-table-column
                    prop="desktop_num"
                    :label="$t('desktopManage.desktop')"
                  >
                  </el-table-column>
                  <!-- 状态 -->
                  <el-table-column
                    prop="online"
                    :label="$t('desktopManage.status')"
                    :formatter="
                      (row, column) => {
                        if (row.online === true) {
                          return $t('desktopManage.online').toString();
                        } else if (row.online === false) {
                          return $t('desktopManage.offline').toString();
                        }
                        return '';
                      }
                    "
                  >
                  </el-table-column>
                  <el-table-column :label="$t('common.action')" width="150">
                    <!-- 管理桌面 -->
                    <template #default="props">
                      <link-button
                        :content="
                          $t('desktopManage.operation.managementDesktop')
                        "
                        :size="10"
                        :font-size="'12px'"
                        @click="
                          $router.push({
                            name: 'DaaSDesktopPoolDetail',
                            query: {
                              poolid: props.row.id,
                            },
                          }).catch(()=>{})
                        "
                      />
                    </template>
                  </el-table-column>
                </template>
              </basic-table>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-scrollbar>
    </div>
  </div>
</template>
<script lang="ts">
import Vue from "vue";
import BasicTable from "../../../components/Basic/Table/BasicTable.vue";
import LinkButton from "../../../components/Basic/Button/LinkButton.vue";
import DesktopPoolOperationFormDialog from "./../components/desktopPoolOperationFormDialog.vue";
import DesktopPoolSelectFormDialog from "./../components/desktopPoolSelectFormDialog.vue";
import DesktopPoolPolicyFormDialog from "./../components/desktopPoolPolicyFormDialog.vue";
import DesktopPoolSendMessageFormDialog from "./../components/desktopPoolSendMessageFormDialog.vue";
import { active } from "sortablejs";
export default Vue.extend({
  components: {
    BasicTable,
    LinkButton,
    DesktopPoolOperationFormDialog,
    DesktopPoolSelectFormDialog,
    DesktopPoolPolicyFormDialog,
    DesktopPoolSendMessageFormDialog,
  },
  data() {
    return {
      searchValue: "",
      resource_value: "",
      tenant_value: "",
      Horizon_resource_value: "",
      Horizon_tenant_value: "",
      resource_options: [],
      tenant_options: [],
      HorizonResource_options: [],
      HorizonTenant_options: [],
      loading: false,
      activeName: "HorizonTable",
      tableSearch: false,
      isAllHorizon: false,
      isAllDass: false
    };
  },
  created() {
    if (localStorage.getItem("activeName")) {
      this.activeName = localStorage.getItem("activeName") as any;
    }
    if (this.activeName === "HorizonTable") {
      (this as any).getHorizonResourceData(false);
    } else {
      (this as any).getResourceData(false);
    }
  },
  watch: {
    resource_value(val, oldVal) {
      if(val == 'all') {
        (this as any).isAllDass = false;
      }else {
        (this as any).isAllDass = true;
      }
    },
    Horizon_resource_value(val, oldVal) {
      if(val == 'all') {
        (this as any).isAllHorizon = false;
      }else {
        (this as any).isAllHorizon = true;
      }
    },
    activeName(newVal, oldVal) {
      this.loading = true;
      localStorage.setItem("resource_value", this.resource_value);
      localStorage.setItem("tenant_value", this.tenant_value);
      localStorage.setItem(
        "Horizon_resource_value",
        this.Horizon_resource_value
      );
      localStorage.setItem("Horizon_tenant_value", this.Horizon_tenant_value);
      localStorage.setItem("activeName", this.activeName);
      if (this.activeName === "HorizonTable") {
        this.loading = false;
        (this as any).getHorizonResourceData(false);
      } else {
        this.loading = false;
        (this as any).getResourceData(false);
      }
    },
  },
  beforeDestroy() {
    localStorage.setItem("resource_value", this.resource_value);
    localStorage.setItem("tenant_value", this.tenant_value);
    localStorage.setItem("Horizon_resource_value", this.Horizon_resource_value);
    localStorage.setItem("Horizon_tenant_value", this.Horizon_tenant_value);
    localStorage.setItem("activeName", this.activeName);
  },
  methods: {
    // 页面刷新重置page
    tableSearchChange(table: any) {
      (this as any).tableSearch = true;
      table.table.refresh(true);
    },
    handleChange() {},
    syncDesktopPool() {
      // 桌面池同步
      this.loading = true;
      const promiseArray = [];
      if (this.activeName === "HorizonTable") {
        promiseArray.push(
          (this as any).$pandaApi.syncDesktops("HorizonView")
        );
      } else {
        promiseArray.push(
          (this as any).$pandaApi.syncDesktops("HorizonDaas")
        );
      }
      Promise.all(promiseArray)
        .then((res: any) => {
          this.loading = false;
          try {
            (this.$refs[`${this.activeName}`] as any).refresh();
          } catch (error) {
            
          }
          this.$message({
            message: this.$t("desktopManage.message.syncSuccess").toString(),
            type: "success",
          });
        })
        .catch((err: any) => {
          this.loading = false;
          this.$message({
            message: this.$t("desktopManage.message.syncFail").toString(),
            type: "warning",
          });
        });
    },
    // 获取资源池数据 isSelect 是否通过选择框调用
    getResourceData(isSelect: boolean) {
      this.loading = true;
      (this as any).$pandaApi.apiGetResourceList().then((res: any) => {
        this.loading = false;
        // 获取资源池列表
        // 初始化资源池选择数据
        this.resource_options = [];
        // 如果接口有返回数据
        if (res.length > 0) {
          res = res.sort((a: any, b: any) => (a.name).localeCompare((b.name), 'zh-Hans-CN', { sensitivity: 'accent' }));
          res.forEach((item: any) => {
            // 如果该资源池下有daas租户
            if (item.daas_resources > 0) {
              // 判断缓存中是否存在资源池id信息并且该id是否为当前资源池id 如果是通过选择框选择，跳过
              if (
                localStorage.getItem("resource_value") &&
                localStorage.getItem("resource_value") == item.id &&
                isSelect === false
              ) {
                // 将缓存中的id放入选择器中的value
                (this as any).resource_value = parseInt(
                  localStorage.getItem("resource_value") as any
                );
              }
              // 添加资源池选择数据
              const param: any = {};
              param.name = item.name;
              param.id = item.id;
              (this.resource_options as any).push(param);
            }
          });
          // 如果上述过程没给value赋值，默认选择资源池选择数据第一个
         (this.resource_options as any).unshift({ id: "all", name: this.$t('desktopManage.allResourcePool') as any });
          if (this.resource_value === "") {
            this.resource_value = (this.resource_options as any)[0].id;
          }
        } else {
          (this.resource_options as any).push({id: 'all', name: this.$t('desktopManage.allResourcePool') as any});
          this.resource_value = 'all';
        }
        // 获取资源租户数据
        this.getResourceTenantData(isSelect);
      }).catch(() => {
        this.loading = false;
      });
    },
    // 获取资源租户数据 isSelect 是否通过选择器选择
    getResourceTenantData(isSelect: boolean) {
       if (this.resource_value === 'all') {
        this.tenant_options = [];
        (this.tenant_options as any).unshift({id: 'all', name: this.$t('desktopManage.allResourceTenant') as any})
        this.tenant_value = 'all';
        (this.$refs[`${this.activeName}`] as any).refresh();
      } else {
        this.loading = true;
        (this as any).$pandaApi
        .apiGetResourceTenantsList(this.resource_value, {})
        .then((res: any) => {
          // 获取资源租户列表
          this.loading = false;
          // 初始化资源租户数据
          this.tenant_options = [];
          this.tenant_value = "";
          // 判断是否有数据，以下步骤与获取资源池相同
          if (res.length > 0) {
            res = res.sort((a: any, b: any) => (a.name).localeCompare((b.name), 'zh-Hans-CN', { sensitivity: 'accent' }));
            res.forEach((item: any) => {
              if (item.resource_type === "HorizonDaas") {
                if (
                  localStorage.getItem("tenant_value") &&
                  localStorage.getItem("tenant_value") == item.id &&
                  isSelect === false
                ) {
                  (this as any).tenant_value = parseInt(
                    localStorage.getItem("tenant_value") as any
                  );
                }
                const param: any = {};
                param.name = item.name;
                param.id = item.id;
                param.resource_type = item.resource_type;
                (this.tenant_options as any).push(param);
              }
            });
            if (this.tenant_value === "") {
              if (this.tenant_options.length > 0) {
                this.tenant_value = (this.tenant_options as any)[0].id;
              }
            }
          } else {
            this.tenant_value = "";
          }
          (this.$refs[`${this.activeName}`] as any).refresh();
          this.loading = false;
          (this.$refs[`${this.activeName}`] as any).loading = false;
        }).catch(() => {
          this.loading = false;
        });
      }
    },
    getHorizonResourceData(isSelect: boolean) {
      this.loading = true;
      (this as any).$pandaApi.apiGetResourceList().then((res: any) => {
        this.loading = false;
        // 获取资源池列表
        this.HorizonResource_options = [];
        if (res.length > 0) {
          res = res.sort((a: any, b: any) => (a.name).localeCompare((b.name), 'zh-Hans-CN', { sensitivity: 'accent' }));
          res.forEach((item: any) => {
            if (item.horizon_resources > 0) {
              // 判断缓存中是否存在资源池id信息并且该id是否为当前资源池id 如果是通过选择框选择，跳过
              if (
                localStorage.getItem("Horizon_resource_value") &&
                localStorage.getItem("Horizon_resource_value") == item.id &&
                isSelect === false
              ) {
                (this as any).Horizon_resource_value = parseInt(
                  localStorage.getItem("Horizon_resource_value") as any
                );
              }
              // 添加资源池选择数据
              const param: any = {};
              param.name = item.name;
              param.id = item.id;
              (this.HorizonResource_options as any).push(param);
            }
          });
          (this.HorizonResource_options as any).unshift({ id: "all", name: this.$t('desktopManage.allResourcePool') as any });
            if (this.Horizon_resource_value === "") {
              this.Horizon_resource_value = (this.HorizonResource_options as any)[0].id;
            }
          } else {
            (this.HorizonResource_options as any).push({id: 'all', name: this.$t('desktopManage.allResourcePool') as any});
            this.Horizon_resource_value = 'all';
          }
          this.getHorizonResourceTenantData(isSelect);
      }).catch(() => {
        this.loading = false;
      });
    },
    getHorizonResourceTenantData(isSelect: boolean) {
      if (this.Horizon_resource_value === 'all') {
        this.HorizonTenant_options = [];
        (this.HorizonTenant_options as any).unshift({id: 'all', name: this.$t('desktopManage.allResourceTenant') as any})
        this.Horizon_tenant_value = 'all';
        (this.$refs[`${this.activeName}`] as any).refresh(true);
      } else {
        this.loading = true;
        (this as any).$pandaApi
        .apiGetResourceTenantsList(this.Horizon_resource_value, {})
        .then((res: any) => {
          this.loading = false;
          // 获取资源租户列表
          this.HorizonTenant_options = [];
          this.Horizon_tenant_value = "";
          // if (res.length > 0) {
          //   res = res.sort((a: any, b: any) => (a.name).localeCompare((b.name), 'zh-Hans-CN', { sensitivity: 'accent' }));
          //   res.forEach((item: any) => {
          //     if (item.resource_type === "HorizonView") {
          //       if (
          //         localStorage.getItem("Horizon_tenant_value") &&
          //         localStorage.getItem("Horizon_tenant_value") == item.id &&
          //         isSelect === false
          //       ) {
          //         (this as any).Horizon_resource_value = parseInt(
          //           localStorage.getItem("Horizon_tenant_value") as any
          //         );
          //       }
              
          //       const param: any = {};
          //       param.name = item.name;
          //       param.id = item.id;
          //       param.resource_type = item.resource_type;
          //       (this.HorizonTenant_options as any).push(param);
          //     }
          //   });
          //   if (this.Horizon_tenant_value === "") {
          //     if (this.HorizonTenant_options.length > 0) {
          //       this.Horizon_tenant_value = (
          //         this.HorizonTenant_options as any
          //       )[0].id;
          //     }
          //   }
          // } else {
          //   this.Horizon_tenant_value = "";
          // }
          if (res.length > 0) {
            res = res.sort((a: any, b: any) =>
              a.name.localeCompare(b.name, "zh-Hans-CN", {
                sensitivity: "accent",
              })
            );
            res.forEach((item: any) => {
              if (
                localStorage.getItem("Horizon_tenant_value") &&
                localStorage.getItem("Horizon_tenant_value") ==
                  item.id &&
                isSelect === false
              ) {
                (this as any).Horizon_tenant_value = parseInt(
                  localStorage.getItem("Horizon_tenant_value") as any
                );
              }
              if (item.resource_type === "HorizonView") {


                const param: any = {};
                param.name = item.name;
                param.id = item.id;
                param.resource_type = item.resource_type;
                (this.HorizonTenant_options as any).push(param);
              }
            });
            if (
              this.Horizon_tenant_value === "" &&
              this.HorizonTenant_options.length > 0
            ) {
              this.Horizon_tenant_value = (
                this.HorizonTenant_options as any
              )[0].id;
            }
          } else {
            this.Horizon_tenant_value = "";
          }
          (this.$refs[`${this.activeName}`] as any).refresh(true);
          this.loading = false;
          (this.$refs[`${this.activeName}`] as any).loading = false;
        }).catch(() => {
          this.loading = false;
        });
      }
    },
  },
});
</script>
<style lang="scss" scoped>
.page-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #eff1f4;

  .page-header {
    height: 60px;
    background-color: #ffffff;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #d9d9d9;

    .page-tile {
      color: #031129;
      font-size: 16px;
      margin-left: 20px;

      .iconzhongyiicon_gaojing {
        margin-left: 5px;
      }
    }
  }

  .page-content {
    height: calc(100vh - 110px);
    overflow: hidden;
    flex-grow: 1;

    .content-wrapper {
      padding: 15px;

      ::v-deep .el-card__body {
        padding-top: 10px;

        .el-tabs__header.is-top {
          margin-bottom: 20px;
        }
      }
    }
  }
}

.table-left-options {
  display: flex;
}

.table-right-options {
  display: flex;

  .setting-button {
    margin-right: 10px;
  }
}
</style>
